package com.sardine.base.design;


import com.sardine.base.design.api.EventDispatcher;
import com.sardine.base.design.api.IContextConfig;
import com.sardine.base.design.api.ListenerHandler;

import java.util.List;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/10/9
 * Time:14:58
 * robot上下文对象
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class RobotContext implements EventDispatcher {
    private static RobotContext context;
    private IContextConfig contextConfig;
    private CommandTrigger trigger;


    public IContextConfig getContextConfig() {
        return contextConfig;
    }

    public void setContextConfig(IContextConfig contextConfig) {
        this.contextConfig = contextConfig;
    }


    private RobotContext() {
        trigger=new CommandTrigger();
    }

    public static synchronized RobotContext getInstance(){
        if(context == null){
            context=new RobotContext();
        }
        return context;
    }

    @Override
    public void dispatcherEvent(RobotEvent event) {
        if(contextConfig == null){
            throw new RuntimeException("未初始化 IContextConfig,请配置RobotListenerContext。增加 spring bean 配置");
        }
        List<ListenerHandler> commend = contextConfig.getCommend(event.getType());
        trigger.activate(commend,event);
    }
}
